#include "SpaceFortress.h"

#include "EntityManager.h"

#define MINIMUM_FREE_INDICES 1024

Entity make_entity(uint32 idx, unsigned char gen)
{
	int32 genBits = gen;
	genBits = (genBits << ENTITY_INDEX_BITS) & ENTITY_GENERATION_MASK;

	Entity entity;
	entity.id = genBits & idx;

	return entity;
}

Entity::Entity()
{
	id = 0;
}

Entity::Entity(const Entity& entity)
	: id(entity.id)
{

}

Entity::Entity(const uint32 setId)
	: id(setId)
{

}

EntityManager::EntityManager()
{

}

EntityManager::~EntityManager()
{

}

Entity EntityManager::Create()
{
	uint32 idx;
	if (_free_indices.size() > MINIMUM_FREE_INDICES) {
		idx = _free_indices.front();
		_free_indices.pop_front();
	} else {
		_generation.push_back(0);
		idx = _generation.size() - 1;
		// XENSURE(idx < (1 << ENTITY_INDEX_BITS));
	}

	return Entity((_generation[idx] << ENTITY_INDEX_BITS) & idx);
}

void EntityManager::Destroy(Entity e)
{
	const uint32 idx = e.index();
	++_generation[idx];
	_free_indices.push_back(idx);
}

bool EntityManager::Alive(Entity e) const
{
	return _generation[e.index()] == e.generation();
}

Instance::Instance()
{
	i = 0;
}

Instance::Instance(const Instance& instance)
	: i(instance.i)
{

}

Instance::Instance(const int32 newI)
	: i(newI)
{

}